/**
 * 共有逻辑的处理与接口
 */

var testOnly = false;

// 本游戏的最大注单数
var _maxBetCount = 0;
function checkBetCount(count) {
    // 注单数没有限制
    if (_maxBetCount == 0) return true;
    var curr = Lottery.totalCount(Lottery.curr());
    if (curr + count <= _maxBetCount) return true;

    var t = Math.max(0, _maxBetCount - curr);
    alert2("下注单数超过上限，投注失败！<br/>当前还可以下注：" + t + "注！", true);
    return false;
}

/**
 * 初始化游戏页面
 */
function initGame(game, cb, useNumber) {
    $(".menu6 .open_result").attr("href", switchCenter("开奖结果", get_game_display_name(game)));
    $(".menu6 .game_rule").attr("href", switchCenter("游戏规则", get_game_display_name(game))); 
    $(".menu6 a.wjmx").attr("href", switchCenter("我的投注", "未结明细"));
    $(".menu6 .center").attr("href", switchCenter("会员专区", "个人资讯"));
    $(".menu6 .baobiao").attr("href", switchCenter("我的报表", "报表查询"));
    $(".menu6 a.today").attr("href", switchCenter("我的投注", "今日已结"));
    $("#left a.charge").click(function() {
        if (context.user && context.user.user.mobile) window.open(switchCenter("资金管理", "我要充值"));
        else alert2("请先注册为正式会员！", true);
    });
    $("#left a.take").click(function() {
        if (context.user && context.user.mobile) window.open(switchCenter("资金管理", "我要取款"));
        else alert2("请先注册为正式会员！", true);
    });

    $(".logo div").html(get_game_display_name(game));
    $(".account-info .account_title a").click(function() {
        if (!context.user.user.mobile) {
            window.open(Util.genUrl({
                file: 'index.html',
                register: 1,
            }));
            return;
        }
        window.open(Util.genUrl({
            file: 'center.html'
        }));
    });

    Classify.query("bet.count", game, false, '0', function(v) {
        _maxBetCount = parseInt(v);
    });

    // 消息弹窗
    {
        Notice.init();
    }
    Notice.loop();

    // 音效开关
    var drawSound = function() {
        $("#top .sound").attr("class", Util.isMute() ? "sound sound-close" : "sound");
    };
    $("#top .sound").click(function() {
        if (Util.isMute()) Util.setMute(0);
        else Util.setMute(1);
        drawSound();
    });
    drawSound();
    
    var register_tab_index = function(tab, index) {
        tab.click(function() {
            $('.am-tabs').tabs('open', index);
        })
    }
    var arr = $(".zy-tabs li");
    for (var i = 0; i < arr.length; i++) register_tab_index($(arr[i]), i);

    // 查看某一期的结果
    var f = function() {
        var c = Result.last();
        if (!c) return;
        window.open(switchCenter("我的投注", "中奖查询", {
            game: game,
            issue: c.issue
        }));
    };
    $("#top .result").popover({
        content: "点击查看本期输赢信息",
        theme: "warning lg",
        trigger: "hover focus"
    });
    $("#top .result").click(function() {
        f();
    });
    $("#top .result2").popover({
        content: "点击查看本期输赢信息",
        theme: "warning lg",
        trigger: "hover focus"
    });
    $("#top .result2").click(function() {
        f();
    });

    // 开奖结果
    Result.switchGame(game);
    Result.cb = function() {
        // 开奖提醒
        var c = Result.last();
        if (c)
            set_lastest_result(c.issue, c.red, useNumber);
        else
            set_lastest_result();

        // 倒计时
        c = Result.curr();
        if (c) {
            var open = c.open / 1000,
                end = c.end / 1000;
            context.curr[game] = c.issue;
            set_countdown(parseInt(open - get_server_time()), parseInt(end - get_server_time()), c.issue, c.betEnable);
        }
    };
    Result.refreshListCb = function() {
        // 更新长龙
        var list = gameRule.long(context.result[game]);
        set_long_queue(list);

        if (window.updateLuZhu) window.updateLuZhu(context.result[game]);
    };

    // 投注记录
    Lottery.switchGame(game);
    Lottery.cb = function() {
        var lottery = context.lottery[game];
        if (!isEmpty(lottery)) {
            // 填充进来
            var map = gameRule.map;
            for (var k in lottery) {
                if (k == "targets") continue;
                if (isEmpty(map[k])) {
                    console.log("不存在的类型", k);
                    continue;
                }
                map[k].rate = lottery[k].value;
            }
        }
        refresh_bet_items();

        // 填充下注列表
        refresh_curr_bet_list();
    };
    
    // 填入筹码输入框
    scan_counter_confirm();

    // 回调填充内容
    cb();
    scan_bet_items();

    // 账号信息改变的回调
    ME.cb = function() {
        set_account_info(ME.get_name(), ME.balance(), ME.pending());
        Result.todayProfit(function(r) {
            var arr = $(".today_win");
            for (var i = 0; i < arr.length; i++) {
                $(arr[i]).html(r.amount/100);
                //$(arr[i]).html("--");
            }
        });
        if (context.user) {
            if (!context.user.user.mobile) {
                // 游客
                $("#left .account_title a").html("立即注册>>");
            }
        }
    };
    ME.cb();

    // 赢的提示
    Result.gotWin = function(list) {
        // 播放声音
        Util.playWinMusic();

        // 显示提示框
        show_bonus_clue(list);
    };

    // 定期抓取赢的数据
    setInterval(function() {
        Result.bet_win_query();
    }, 5 * 1000);
}

/**
 * 当前是否可以下注
 */
function can_bet() {
    var c = Result.curr();
    if (!c || !isEmpty(c.red)) return false;
    if (c.end/1000 - get_server_time() <= 0) return false;
    return true;
}

/**
 * 设置最近一期的开奖结果
 * name为第几期, list为结果列表，例如：
 * set_lastest_result("165230", [3, 3, 2, 1, 5, 6, 7, 8, 9, 10])
 */
function set_lastest_result(name, list, useNumber) {
    if (name)
        $("#periods").html("<span class='yellow'>" + name + "</span> 期开奖结果");
    else
        $("#periods").html("-- 期开奖结果");
    var r = $(".result2");
    r.html("");

    if (list && window.parseLastestResult)
        list = parseLastestResult(list);

    if (list) {
        for (var i in list) {
            if (window.customDrawResult)
                // 使用自定义的绘制方法
                var line = '<div class="item item__index__">' + window.customDrawResult(list[i]) + '</div>';    
            else if (!useNumber)
                var line = '<div class="item item__index__"><img src="../public/all/images/__i__.png" /></div>';
            else {
                var line = '<div class="item item__index__">__i__</div>';
            }
                
            if (i == list.length - 1)
                line = line.replace(/__index__/, parseInt(list[i]) + " item_last");
            else
                line = line.replace(/__index__/, parseInt(list[i]));
            line = line.replace(/__i__/, list[i]);
            r.append(line);
        }
    }
}

/**
 * 开启倒计时，单位为秒
 * 分别为开奖倒计时和封盘倒计时
 */
function set_countdown(openTime, closeTime, issue, betEnable) {
    betEnable = betEnable === undefined ? true : betEnable;
    if (timer)  {
        clearTimeout(timer);
        timer = 0;
    }
    if (!issue) {
        $(".current .issue").html("-- 期");
        $("#kj_cd").html("00:00");
        $("#fp_cd").html("00:00");
        on_fengpan();
        return;
    }

    start = new Date().getTime()/1000;
    var f = function() {
        var delta = new Date().getTime()/1000 - start;
        var t = openTime - delta;
        if (t < 0 || !t) t = 0;
        if (t >= 3600) {
            var hour = parseInt(t / 3600);
            if (hour < 10) hour = "0" + hour;
            t = t % 3600;
            var min = parseInt(t / 60);
            if (min < 10) min = "0" + min;
            t = Math.ceil(t % 60);
            if (t < 10) t = "0" + t;
            $("#kj_cd").html((hour) + ":" + min + ":" + t);
        }
        else {
            var i1 = parseInt(t / 60), i2 = Math.ceil(t % 60);
            $("#kj_cd").html((i1 < 10 ? "0" + i1 : i1) + ":" + (i2 < 10 ? "0" + i2 : i2));
        }

        t = closeTime - delta;
        if (t < 0 || !t) t = 0;
        if (t >= 3600) {
            var hour = parseInt(t / 3600);
            if (hour < 10) hour = "0" + hour;
            t = t % 3600;
            var min = parseInt(t / 60);
            if (min < 10) min = "0" + min;
            t = Math.ceil(t % 60);
            if (t < 10) t = "0" + t;
            $("#fp_cd").html((hour) + ":" + min + ":" + t);
        }
        else {
            var i1 = parseInt(t / 60), i2 = Math.ceil(t % 60);
            $("#fp_cd").html((i1 < 10 ? "0" + i1 : i1) + ":" + (i2 < 10 ? "0" + i2 : i2));
        }

        if (t == 0 || !betEnable) on_fengpan();
        else on_kaipan();
    };
    f();
    timer = setInterval(f, 200);

    // 第几期
    $(".current .issue").html("<span class='yellow'>" + issue + "</span> 期")
}
var timer, start;

/**
 * 设置账户信息，参数分别为：账号名称、余额、未结算金额
 * 如果传递undefined，则表示没有变化
 */
function set_account_info(name, money, betMoney) {
    if (name !== undefined)
        $(".account .name").html(name);
    if (money !== undefined)
        $(".account .money").html(money/100 + "");
    if (betMoney !== undefined)
        $(".account .bet_money").html(betMoney/100 + "");
}

/**
 * 设置长龙的信息，参数list为数组，如
 * [
 *     { name: '冠亚大', value: 6 },
 *     ...
 * ]
 */
function set_long_queue(list) {
    var table = $(".long tbody");
    table.empty();
    for (var i in list) {
        var o = list[i];
        var k, v;
        for (var j in o) {
            k = j;
            v = o[j];
        }
        var tr = $("<tr></tr>");

        tr.append("<td>" + k + "</td>");
        tr.append("<td class='qi' style='width:60px;text-align:center;'>" + v + "期</td>");
        table.append(tr);
    }
    if (list.length == 0) {
        table.append("<tr><td colspan='2' align='center'>数据为空</td></tr>")
    }
}

/**
 * 设置投注的历史信息，参数list为数组，如：
 * [{ name: "冠军 大", odds: 1.99, total: 2000  }, ...]
 * 
 */
function set_bet_history(list) {
    var total = 0;
    var table = $(".bet_history tbody");
    table.empty();
    for (var i in list) {
        var o = list[i];
        var tr = $("<tr></tr>");

        tr.append("<td class='name'>" + o.name + "</td>");
        tr.append("<td class='odds'>" + o.odds + "</td>");
        tr.append("<td class='total'>" + o.total/100 + "</td>");
        table.append(tr);
        total += parseInt(o.total);
    }
    if (list.length == 0) {
        table.append("<tr><td colspan='3' align='center'>本期未下注</td></tr>")
    }

    $(".total_bet").html("总金额：<span>" + total/100 + '</span>');
}

/**
 * 弹出提示框
 */
function alert2(message, isWarning) {
    $("#clue_content").html(message);
    $("#clue .clue-icon img").attr("src", "../public/all/images/" + (isWarning ? "warning.png" : "good.png"));
    $("#clue").modal({
        width: 420
    });
}

/**
 * 弹出Loading框
 */
function startLoading() {
    $("#loading").modal({
    });
}
function stopLoading() {
    $("#loading").modal("close");
}

/**
 * 跳转到个人中心
 */
function switchCenter(n1, n2, params) {
    params = params || {};
    if (n1) params.n1 = n1;
    if (n2) params.n2 = n2;
    params.file = 'center.html';
    return Util.genUrl(params);
}

// 刷新本期投注信息
function refresh_curr_bet_list() {
    var bets = context.bets[game] || {};
    var issue = Lottery.curr() || "";
    bets = bets[issue] || [];

    // 对同一组的信息做下合并
    var data = Lottery.combineGroup(bets);

    var list = [];
    for (var k in data) {
        var o = data[k];
        if (o.group) {
            k = o.group.split("_")[0];
        }
        else k = gameRule.getTargetName(o.target);

        list.push({
            name: k,
            odds: o.rate,
            total: o.amount
        });
    }
    set_bet_history(list);
}

// 显示某期的盈利结果
function show_profit_view(type, issue, result) {
    $("#popup .title img").attr("src", "../public/all/images/title-result.png");
    Lottery.today(function(r) {
        switch_page("profit", $('#popup_content'), function() {
            // 填充数据
            $(".profit-view .issue").html(issue + "期");
            $(".profit-view .total").html(result.amount/100);
            $(".profit-view .profit").html(result.profit/100);
        });
        $("#popup").modal({
            width:1024,
        });
    });
}

/**
 * 显示中奖提示框
 */
function show_bonus_clue(list) {
    var content = "";
    for (var i in list) {
        var item = list[i];
        content += get_game_display_name(item.type) + "第" + item.issue + "期 " + Util.convertTarget(item.type, item.target) +
            " 中奖：<span class='red'>" + (item.amount/100).toFixed(2) + "</span><br/>";
    }

    $(".bonus-clue .c").html(content);
    $(".bonus-clue").show();

    // 延迟关闭
    setTimeout(function() {
        $(".bonus-clue").hide();
    }, 10000);

    $(".bonus-clue .close").click(function() {
        $(".bonus-clue").hide();
    });
}

// 配置url
context.config.page_url = urlInfo.protocol + "://" + urlInfo.host + (urlInfo.path.replace(urlInfo.file, "")) + "pages/";
context.config.center = urlInfo.protocol + "://" + urlInfo.host + (urlInfo.path.replace(urlInfo.file, "")) + "center.html";
